'''
Created on 2011-9-28

@author: 123kangta
'''
import socket
from core.ws_request import WebSocketRequest
from core.session import Session
from core.container import DefaultContainer
from core.handle import HeaderInfo

applicationContext = DefaultContainer()
server = None

def create_socket_server(ip="127.0.0.1", port=9999):
    """
        不需要提供任何服务，用于socket连接即可
    """
    global server
    if not server:
        server = socket.socket()
        server.bind((ip, port))
        server.listen(100)
        server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    #    def run_forever():
    #        while True:
    #            server.accept();
    #
    #    t = threading.Thread(target=run_forever)
    #    t.start()
    return server


def create_socket(ip="127.0.0.1", port=9999):
    return socket.create_connection((ip, port))


def create_session(addr="127.0.0.1"):
    session = Session(create_socket(), applicationContext, handle=create_handle(), *(addr, ""))
    session.data = "仅用作测试"
    return session


def create_request():
    return WebSocketRequest(create_session())


def create_handle():
    class Handle():
        def __init__(self):
            self.header_info = HeaderInfo()
            self.header_info.host = "172.0.0.1"
            self.header_info.origin = "172.0.0.1"
            self.header_info.parameters = dict()
            self.header_info.uri = "/"


        def handshake(self):
            return ""

        def validate(self):
            return True

        def send_data(self, data, clients=None, closed=False):
            pass

        def recv_data(self, count=256):
            pass

        def close_socket(self):
            pass

    return Handle()


